<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\CourseOutline;
use app\model\TeachingPlan;
use think\facade\Db;

class CourseOutlineController extends BaseController
{
    /**
     * 获取课程列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);
        $status = $request->param('status');

        $query = CourseOutline::where('user_id', $user->id);
        
        if (isset($status)) {
            $query->where('status', $status);
        }

        $courses = $query->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        // 获取每个课程的教案详情
        $formattedCourses = array_map(function($course) {
            $data = $course->toArray();
            $data['teaching_plans'] = TeachingPlan::whereIn('id', $course->teaching_plan_ids)
                ->field('id,title,total_elements,lecture_count,question_count')
                ->select()
                ->toArray();

            // 获取AI角色信息
            $aiRole = null;
            if ($course->ai_roles_id > 0) {
                $aiRole = Db::name('ai_roles')
                    ->where('id', $course->ai_roles_id)
                    ->field('id,name,avatar,description')
                    ->find();
            }
            $data['ai_role'] = $aiRole;

            return $data;
        }, $courses->items());

        return json([
            'status' => 200,
            'data' => [
                'total' => $courses->total(),
                'current_page' => $courses->currentPage(),
                'last_page' => $courses->lastPage(),
                'courses' => $formattedCourses
            ]
        ]);
    }

    /**
     * 创建课程
     */
    public function create(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title'])) {
            return json(['status' => 400, 'message' => '请填写课程标题']);
        }

        try {
            $course = new CourseOutline;
            $course->user_id = $user->id;
            $course->title = $data['title'];
            $course->description = $data['description'] ?? '';
            $course->cover_image = $data['cover_image'] ?? '';
            $course->teaching_plan_ids = $data['teaching_plan_ids'] ?? [];
            $course->recommended_course_ids = $data['recommended_course_ids'] ?? [];
            $course->total_plans = count($data['teaching_plan_ids'] ?? []);
            $course->status = CourseOutline::STATUS_DRAFT;
            $course->ai_roles_id = $data['ai_roles_id'] ?? 0;
            $course->save();

            return json([
                'status' => 200,
                'message' => '课程创建成功',
                'data' => $course
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新课程基本信息
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $courseId = $request->param('id');
        $data = $request->post();

        $course = CourseOutline::where('id', $courseId)
            ->where('user_id', $user->id)
            ->find();

        if (!$course) {
            return json(['status' => 404, 'message' => '课程不存在或无权限']);
        }

        try {
            $updateData = [];
            if (isset($data['title'])) $updateData['title'] = $data['title'];
            if (isset($data['description'])) $updateData['description'] = $data['description'];
            if (isset($data['cover_image'])) $updateData['cover_image'] = $data['cover_image'];
            if (isset($data['recommended_course_ids'])) {
                $updateData['recommended_course_ids'] = $data['recommended_course_ids'];
            }
            if (isset($data['ai_roles_id'])) $updateData['ai_roles_id'] = $data['ai_roles_id'];
            
            $course->save($updateData);
            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新课程状态
     */
    public function updateStatus(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $courseId = $request->param('id');
        $status = $request->param('status');

        if (!in_array($status, [
            CourseOutline::STATUS_DRAFT,
            CourseOutline::STATUS_PUBLISHED,
            CourseOutline::STATUS_OFFLINE
        ])) {
            return json(['status' => 400, 'message' => '无效的状态值']);
        }

        $course = CourseOutline::where('id', $courseId)
            ->where('user_id', $user->id)
            ->find();

        if (!$course) {
            return json(['status' => 404, 'message' => '课程不存在或无权限']);
        }

        try {
            $course->status = $status;
            $course->save();
            return json(['status' => 200, 'message' => '状态更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除课程
     */
    public function delete(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $courseId = $request->param('id');

        $course = CourseOutline::where('id', $courseId)
            ->where('user_id', $user->id)
            ->find();

        if (!$course) {
            return json(['status' => 404, 'message' => '课程不存在或无权限']);
        }

        try {
            $course->delete();
            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取课程详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $courseId = $request->param('id');
        
        try {
            $course = CourseOutline::where('id', $courseId)
                ->where('user_id', $user->id)
                ->find();

            if (!$course) {
                return json(['status' => 404, 'message' => '课程不存在']);
            }

            // 获取教案详情
            $teachingPlans = TeachingPlan::whereIn('id', $course->teaching_plan_ids)
                ->select()
                ->toArray();

            // 获取推荐课程
            $recommendedCourses = [];
            if (!empty($course->recommended_course_ids)) {
                $recommendedCourses = CourseOutline::whereIn('id', $course->recommended_course_ids)
                    ->field('id,title,description,cover_image')
                    ->select()
                    ->toArray();
            }

            $data = $course->toArray();
            $data['teaching_plans'] = $teachingPlans;
            $data['recommended_courses'] = $recommendedCourses;

            // 获取AI角色信息
            $aiRole = null;
            if ($course->ai_roles_id > 0) {
                $aiRole = Db::name('ai_roles')
                    ->where('id', $course->ai_roles_id)
                    ->field('id,name,avatar,description')
                    ->find();
            }
            $data['ai_role'] = $aiRole;

            return json([
                'status' => 200,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '获取失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新课程教案编排
     */
    public function updatePlans(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $courseId = $request->param('id');
        $teachingPlanIds = $request->post('teaching_plan_ids', []); // 按顺序排列的教案ID数组

        $course = CourseOutline::where('id', $courseId)
            ->where('user_id', $user->id)
            ->find();

        if (!$course) {
            return json(['status' => 404, 'message' => '课程不存在或无权限']);
        }

        // 验证所有教案是否存在且属于当前用户
        $validPlans = TeachingPlan::whereIn('id', $teachingPlanIds)
            ->where('user_id', $user->id)
            ->column('id');

        if (count($validPlans) !== count($teachingPlanIds)) {
            return json(['status' => 400, 'message' => '存在无效的教案ID']);
        }

        try {
            $course->teaching_plan_ids = $teachingPlanIds;
            $course->total_plans = count($teachingPlanIds);
            $course->save();

            return json(['status' => 200, 'message' => '教案编排更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }
} 